/*
 * Copyright 2010 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.namuan.jp_stock.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.UUID;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

/**
 * Utility class supporting the Facebook Object.
 *
 * @author ssoneff@facebook.com
 *
 */
public final class Util {

    /**
     * Generate the multi-part post body providing the parameters and boundary
     * string
     * 
     * @param parameters the parameters need to be posted
     * @param boundary the random string as boundary
     * @return a string of the post body
     */
    public static String encodePostBody(Bundle parameters, String boundary) {
        if (parameters == null) return "";
        StringBuilder sb = new StringBuilder();

        for (String key : parameters.keySet()) {
            if (parameters.getByteArray(key) != null) {
                continue;
            }

            sb.append("Content-Disposition: form-data; name=\"" + key +
                    "\"\r\n\r\n" + parameters.getString(key));
            sb.append("\r\n" + "--" + boundary + "\r\n");
        }

        return sb.toString();
    }

    public static String encodeUrl(Bundle parameters) {
        if (parameters == null) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String key : parameters.keySet()) {
            if (first) first = false; else sb.append("&");
            sb.append(URLEncoder.encode(key) + "=" +
                      URLEncoder.encode(parameters.getString(key)));
        }
        return sb.toString();
    }
   
    public static Bundle decodeUrl(String s) {
        Bundle params = new Bundle();
        if (s != null) {
            String array[] = s.split("&");
            for (String parameter : array) {
                String v[] = parameter.split("=");
                params.putString(URLDecoder.decode(v[0]),
                                 URLDecoder.decode(v[1]));
            }
        }
        return params;
    }

    /**
     * Parse a URL query and fragment parameters into a key-value bundle.
     *
     * @param url the URL to parse
     * @return a dictionary bundle of keys and values
     */
    public static Bundle parseUrl(String url) {
        // hack to prevent MalformedURLException
        url = url.replace("fbconnect", "http");
        try {
            URL u = new URL(url);
            Bundle b = decodeUrl(u.getQuery());
            b.putAll(decodeUrl(u.getRef()));
            return b;
        } catch (MalformedURLException e) {
            return new Bundle();
        }
    }

    
    /**
     * Connect to an HTTP URL and return the response as a string.
     *
     * Note that the HTTP method override is used on non-GET requests. (i.e.
     * requests are made as "POST" with method specified in the body).
     *
     * @param url - the resource to open: must be a welformed URL
     * @param method - the HTTP method to use ("GET", "POST", etc.)
     * @param params - the query parameter for the URL (e.g. access_token=foo)
     * @return the URL contents as a String
     * @throws HttpException 
     * @throws MalformedURLException - if the URL format is invalid
     * @throws IOException - if a network problem occurs
     */
    public static String openUrl(String url, String methods, Bundle params) throws HttpException, IOException {
    	HttpClient client = new HttpClient();
    	
    	Log.d("@@@@@@@@@@@@@@@@@@@@@",params.toString());
		MultipartPostMethod method = null;
		method=new MultipartPostMethod(url);
		
		if(params.get("file")!=null){
			
			File file =new File(params.get("file").toString());
			method.addParameter("file", file);
		}
    	if(methods.equals("GET")){
    		method.setQueryString(encodeUrl(params));
    	}else if(methods.equals("POST")){
    		method.setQueryString(encodeUrl(params));
    		
    	}
    	 Log.d("Facebook-Util", methods + " URL: " + url);
    	
   	
    	int statusCode = client.executeMethod(method);

    	System.out.println("QueryString>>> "+method.getQueryString());
    	System.out.println("Status Text>>>"
    	+HttpStatus.getStatusText(statusCode));

    	
    	String response=method.getResponseBodyAsString();
    	

        return response;
    }

    private static String read(InputStream in) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }
        in.close();
        return sb.toString();
    }

    public static void clearCookies(Context context) {
        // Edge case: an illegal state exception is thrown if an instance of
        // CookieSyncManager has not be created.  CookieSyncManager is normally
        // created by a WebKit view, but this might happen if you start the
        // app, restore saved state, and click logout before running a UI
        // dialog in a WebView -- in which case the app crashes
        @SuppressWarnings("unused")
        CookieSyncManager cookieSyncMngr =
            CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }
   

   
    /**
     * Parse a server response into a JSON Object. This is a basic
     * implementation using org.json.JSONObject representation. More
     * sophisticated applications may wish to do their own parsing.
     *
     * The parsed JSON is checked for a variety of error fields and
     * a FacebookException is thrown if an error condition is set,
     * populated with the error message and error type or code if
     * available.
     *
     * @param response - string representation of the response
     * @return the response as a JSON Object
     * @throws JSONException - if the response is not valid JSON
     * @throws JustplaceError - if an error condition is set
     */
    public static JSONObject parseJson(String response)
          throws JSONException, JustplaceError {
        // Edge case: when sending a POST request to /[post_id]/likes
        // the return value is 'true' or 'false'. Unfortunately
        // these values cause the JSONObject constructor to throw
        // an exception.
        if (response.equals("false")) {
            throw new JustplaceError("request failed");
        }
        if (response.equals("true")) {
            response = "{value : true}";
        }
        JSONObject json = new JSONObject(response);

        // errors set by the server are not consistent
        // they depend on the method and endpoint
        if (json.has("error")) {
            JSONObject error = json.getJSONObject("error");
            throw new JustplaceError(
                    error.getString("message"), error.getString("type"), 0);
        }
        if (json.has("error_code") && json.has("error_msg")) {
            throw new JustplaceError(json.getString("error_msg"), "",
                    Integer.parseInt(json.getString("error_code")));
        }
        if (json.has("error_code")) {
            throw new JustplaceError("request failed", "",
                    Integer.parseInt(json.getString("error_code")));
        }
        if (json.has("error_msg")) {
            throw new JustplaceError(json.getString("error_msg"));
        }
        if (json.has("error_reason")) {
            throw new JustplaceError(json.getString("error_reason"));
        }
        return json;
    }

    /**
     * Display a simple alert dialog with the given text and title.
     *
     * @param context
     *          Android context in which the dialog should be displayed
     * @param title
     *          Alert dialog title
     * @param text
     *          Alert dialog message
     */
    public static void showAlert(Context context, String title, String text) {
        Builder alertBuilder = new Builder(context);
        alertBuilder.setTitle(title);
        alertBuilder.setMessage(text);
        alertBuilder.create().show();
    }
    

	
		
    public static Options getBitmapSize(Options options){ 
    	        int targetWidth = 0; 
    	        int targetHeight = 0; 
    	        Log.d("@option outWidth",options.outWidth+"");  
    	        Log.d("@option outHeight",options.outHeight+"");  
    	        if(options.outWidth > options.outHeight){     
    	            targetWidth = (int)(480 * 1.3); 
    	            targetHeight = 480; 
    	        }else{ 
    	            targetWidth = 480; 
    	            targetHeight = (int)(480 * 1.3); 
    	        } 
    	  
    	        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math.abs(options.outWidth - targetWidth); 
    	        if(options.outHeight * options.outWidth * 2 >= 16384){ 
    	            double sampleSize = scaleByHeight 
    	                ? options.outHeight / targetHeight 
    	                : options.outWidth / targetWidth; 
    	            options.inSampleSize = (int) Math.pow(2d, Math.floor(Math.log(sampleSize)/Math.log(2d)))*2; 
    	            Log.d("inSampleSize", options.inSampleSize+"");
    	        } 
    	        options.inJustDecodeBounds = false; 
    	        options.inTempStorage = new byte[16*1024]; 
    	          
    	        return options; 
    	    }
    public static Options getProfileBitmapSize(Options options){ 
        int targetWidth = 0; 
        int targetHeight = 0; 
        Log.d("@option outWidth",options.outWidth+"");  
        Log.d("@option outHeight",options.outHeight+"");  
        if(options.outWidth > options.outHeight){     
            targetWidth =50; 
            targetHeight = 50; 
        }else{ 
            targetWidth = 50; 
            targetHeight = 50; 
        } 
  
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math.abs(options.outWidth - targetWidth); 
        if(options.outHeight * options.outWidth * 2 >= 16384){ 
            double sampleSize = scaleByHeight 
                ? options.outHeight / targetHeight 
                : options.outWidth / targetWidth; 
            options.inSampleSize = (int) Math.pow(2d, Math.floor(Math.log(sampleSize)/Math.log(2d))); 
            Log.d("inSampleSize", options.inSampleSize+"");
        } 
        options.inJustDecodeBounds = false; 
        options.inTempStorage = new byte[16*1024]; 
          
        return options; 
    }

	public static String creHtmlBody(String _imageURL) {
		StringBuffer sb = new StringBuffer("<HTML>");
		   sb.append("<HEAD>");     
		   sb.append("</HEAD>");
		   sb.append("<BODY>");
		   sb.append("<img width=\"100%\" src=\""+ _imageURL +"\"/>");
		   sb.append("</BODY>");
		   sb.append("</HTML>");  
		   return sb.toString();  
	}
	public static String getRealPathFromURI(Uri contentUri,Activity activity,boolean isProfilePhoto) {
		 String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION};  
		    Cursor cursor = activity.managedQuery( contentUri, proj,null, null,null);  
		    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		    int ori = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.ORIENTATION);
		    cursor.moveToFirst(); 
		    //Log.d("orein", cursor.getString(ori)!=null?cursor.getString(ori):0+"");
		    ori=Integer.parseInt(cursor.getString(ori)!=null?cursor.getString(ori):0+"");
		    Uri photoUri = Uri.parse(cursor.getString(column_index));
		 File cacheDir;
		 String sdState = android.os.Environment.getExternalStorageState();
			if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
				File sdDir = android.os.Environment.getExternalStorageDirectory();		
				cacheDir = new File(sdDir,"data/codehenge");
			}
			else
				cacheDir = activity.getCacheDir();
			
			if(!cacheDir.exists())
				cacheDir.mkdirs();
		 BitmapFactory.Options options = new BitmapFactory.Options();
		 options.inJustDecodeBounds = true;
		    
	        String uploadImagePath = photoUri.getEncodedPath();
	        
	        Bitmap displayBitmap = BitmapFactory.decodeFile(uploadImagePath, options);
	      
	        if(isProfilePhoto){
	        	options = Util.getProfileBitmapSize(options);
	        }else{
	        	options = Util.getBitmapSize(options);
	        	
	        }
	        
	        displayBitmap = BitmapFactory.decodeFile(uploadImagePath, options);
	        displayBitmap=rotate(displayBitmap,ori);
	        File f = new File(cacheDir, UUID.randomUUID().toString()+".png");
	        FileOutputStream out = null;
			
			try {
				out = new FileOutputStream(f);
				displayBitmap.compress(Bitmap.CompressFormat.PNG, 50, out);
			} catch (Exception e) {
				e.printStackTrace();
			}
			finally { 
				try { if (out != null ) out.close(); }
				catch(Exception ex) {} 
			}
	        
	       
	 
	   return f.getAbsolutePath(); 
	 }
	 public static Bitmap rotate(Bitmap bitmap, int degrees)
	 {
	   if(degrees != 0 && bitmap != null)
	   {
	     Matrix m = new Matrix();
	     m.setRotate(degrees, (float) bitmap.getWidth() / 2, 
	     (float) bitmap.getHeight() / 2);
	     
	     try
	     {
	       Bitmap converted = Bitmap.createBitmap(bitmap, 0, 0,
	       bitmap.getWidth(), bitmap.getHeight(), m, true);
	       if(bitmap != converted)
	       {
	         bitmap.recycle();
	         bitmap = converted;
	       }
	     }
	     catch(OutOfMemoryError ex)
	     {
	       // 메모리가 부족하여 회전을 시키지 못할 경우 그냥 원본을 반환합니다.
	     }
	   }
	   return bitmap;
	 }

}
